<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量文字替换工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5', // 主色调：深紫色
                        secondary: '#10B981', // 辅助色：绿色
                        accent: '#F59E0B', // 强调色：橙色
                        light: '#F3F4F6', // 浅色背景
                        dark: '#1F2937'  // 深色文本
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-height {
                transition: max-height 0.3s ease-in-out;
            }
            .highlight {
                padding: 0 2px;
                border-radius: 2px;
                color: inherit;
            }
        }
    </style>
    
    <style>
        /* 预设的高亮颜色 */
        .highlight-color-0 { background-color: rgba(255, 204, 204, 0.7); } /* 浅红 */
        .highlight-color-1 { background-color: rgba(204, 255, 204, 0.7); } /* 浅绿 */
        .highlight-color-2 { background-color: rgba(204, 204, 255, 0.7); } /* 浅蓝 */
        .highlight-color-3 { background-color: rgba(255, 255, 204, 0.7); } /* 浅黄 */
        .highlight-color-4 { background-color: rgba(255, 204, 255, 0.7); } /* 浅粉 */
        .highlight-color-5 { background-color: rgba(204, 255, 255, 0.7); } /* 浅青 */
        .highlight-color-6 { background-color: rgba(255, 229, 204, 0.7); } /* 浅橙 */
        .highlight-color-7 { background-color: rgba(229, 204, 255, 0.7); } /* 浅紫 */
        
        /* 颜色选择器按钮样式 */
        .color-option {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            cursor: pointer;
            transition: transform 0.2s;
            border: 2px solid transparent;
        }
        .color-option:hover {
            transform: scale(1.1);
        }
        .color-option.selected {
            border-color: #333;
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-light to-white min-h-screen font-sans text-dark">
    <div class="container mx-auto px-4 py-8 max-w-7xl">
        <!-- 页面标题 -->
        <header class="mb-8 text-center">
            <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold text-primary mb-2 text-shadow">
                <i class="fa fa-exchange text-accent mr-3"></i>批量文字替换工具
            </h1>
            <p class="text-gray-600 text-lg max-w-2xl mx-auto">
                高效替换文本中的多个内容，支持批量设置替换规则，所有规则均基于原始文本进行替换
            </p>
        </header>

        <!-- 第一层：功能区 -->
        <section class="bg-white rounded-xl shadow-lg p-6 mb-8 transform transition-all duration-300 hover:shadow-xl">
            <h2 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-cogs text-primary mr-2"></i>功能操作
            </h2>
            
            <div class="flex flex-wrap gap-4 justify-center">
                <!-- 新建替换规则按钮 -->
                <button id="addRule" class="flex items-center px-5 py-3 bg-primary text-white rounded-lg shadow-md hover:bg-primary/90 transition-all transform hover:-translate-y-1 active:translate-y-0">
                    <i class="fa fa-plus-circle mr-2"></i>新建替换规则
                </button>
                
                <!-- 执行替换按钮 -->
                <button id="replaceBtn" class="flex items-center px-5 py-3 bg-secondary text-white rounded-lg shadow-md hover:bg-secondary/90 transition-all transform hover:-translate-y-1 active:translate-y-0">
                    <i class="fa fa-play-circle mr-2"></i>执行替换
                </button>
                
                <!-- 清空所有规则按钮 -->
                <button id="clearRules" class="flex items-center px-5 py-3 bg-amber-500 text-white rounded-lg shadow-md hover:bg-amber-600 transition-all transform hover:-translate-y-1 active:translate-y-0">
                    <i class="fa fa-eraser mr-2"></i>清空所有规则
                </button>
                
                <!-- 清空所有文本按钮 -->
                <button id="clearTexts" class="flex items-center px-5 py-3 bg-red-500 text-white rounded-lg shadow-md hover:bg-red-600 transition-all transform hover:-translate-y-1 active:translate-y-0">
                    <i class="fa fa-trash mr-2"></i>清空所有文本
                </button>
                
                <!-- 加载示例文本按钮 -->
                <button id="loadExample" class="flex items-center px-5 py-3 bg-accent text-white rounded-lg shadow-md hover:bg-accent/90 transition-all transform hover:-translate-y-1 active:translate-y-0">
                    <i class="fa fa-file-text-o mr-2"></i>加载示例文本
                </button>
            </div>
            
            <!-- 替换规则区域 -->
            <div class="mt-6">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                    <i class="fa fa-list-alt text-primary mr-2"></i>替换规则
                    <span id="ruleCount" class="ml-2 text-sm bg-gray-100 px-2 py-1 rounded-full">1 条规则</span>
                </h3>
                
                <div id="rulesContainer" class="space-y-3 max-h-60 overflow-y-auto pr-2">
                    <!-- 初始替换规则行 -->
                    <div class="rule-row flex flex-wrap gap-3 items-end">
                        <div class="flex-1 min-w-[200px]">
                            <label class="block text-sm font-medium text-gray-700 mb-1">要替换的内容</label>
                            <input type="text" class="from-text w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" placeholder="输入要替换的文字">
                        </div>
                        <div class="flex-1 min-w-[200px]">
                            <label class="block text-sm font-medium text-gray-700 mb-1">替换后的内容</label>
                            <input type="text" class="to-text w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" placeholder="输入替换后的文字">
                        </div>
                        <div class="color-selector min-w-[180px]">
                            <label class="block text-sm font-medium text-gray-700 mb-1">选择高亮颜色</label>
                            <div class="flex gap-2">
                                <div class="color-option highlight-color-0 selected" data-color="0"></div>
                                <div class="color-option highlight-color-1" data-color="1"></div>
                                <div class="color-option highlight-color-2" data-color="2"></div>
                                <div class="color-option highlight-color-3" data-color="3"></div>
                                <div class="color-option highlight-color-4" data-color="4"></div>
                            </div>
                            <input type="hidden" class="color-value" value="0">
                        </div>
                        <div class="delete-rule self-center opacity-50 hover:opacity-100 transition-opacity">
                            <button class="p-2 text-gray-500 hover:text-red-500 disabled:opacity-30 disabled:cursor-not-allowed" disabled>
                                <i class="fa fa-times-circle"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 第二层：文字对比区 -->
        <section class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 原始文本区域 -->
            <div class="bg-white rounded-xl shadow-lg p-6 transform transition-all duration-300 hover:shadow-xl">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="text-xl font-semibold flex items-center">
                        <i class="fa fa-file-text text-primary mr-2"></i>原始文本
                    </h2>
                    <span id="originalWordCount" class="text-sm bg-gray-100 px-2 py-1 rounded-full">0 个字</span>
                </div>
                <div id="originalText" class="w-full h-64 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all overflow-auto" contenteditable="true" spellcheck="false">
                    <div class="min-h-full">请输入或粘贴需要处理的文本...</div>
                </div>
            </div>
            
            <!-- 替换后文本区域 -->
            <div class="bg-white rounded-xl shadow-lg p-6 transform transition-all duration-300 hover:shadow-xl">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="text-xl font-semibold flex items-center">
                        <i class="fa fa-file-text-o text-secondary mr-2"></i>替换后文本
                    </h2>
                    <div class="flex items-center gap-2">
                        <span id="resultWordCount" class="text-sm bg-gray-100 px-2 py-1 rounded-full">0 个字</span>
                        <button id="copyResult" class="text-sm px-3 py-1 bg-gray-100 hover:bg-gray-200 rounded-full transition-colors flex items-center">
                            <i class="fa fa-copy mr-1"></i>复制
                        </button>
                    </div>
                </div>
                <div id="resultText" class="w-full h-64 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary/50 focus:border-secondary transition-all overflow-auto" contenteditable="true" spellcheck="false">
                    <div class="min-h-full">替换后的文本将显示在这里...</div>
                </div>
                <div id="copyNotification" class="mt-2 text-sm text-green-600 hidden">
                    <i class="fa fa-check-circle mr-1"></i>已复制到剪贴板
                </div>
            </div>
        </section>

        <!-- 第三层：信息显示区 -->
        <section class="bg-white rounded-xl shadow-lg p-6 transform transition-all duration-300 hover:shadow-xl">
            <h2 class="text-xl font-semibold mb-4 flex items-center">
                <i class="fa fa-bar-chart text-primary mr-2"></i>替换信息
            </h2>
            
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="bg-light rounded-lg p-4">
                    <p class="text-sm text-gray-500 mb-1">原始文本字数</p>
                    <p id="infoOriginalCount" class="text-2xl font-bold text-primary">0</p>
                </div>
                
                <div class="bg-light rounded-lg p-4">
                    <p class="text-sm text-gray-500 mb-1">替换后文本字数</p>
                    <p id="infoResultCount" class="text-2xl font-bold text-secondary">0</p>
                </div>
                
                <div class="bg-light rounded-lg p-4">
                    <p class="text-sm text-gray-500 mb-1">替换规则数量</p>
                    <p id="infoRuleCount" class="text-2xl font-bold text-accent">1</p>
                </div>
                
                <div class="bg-light rounded-lg p-4">
                    <p class="text-sm text-gray-500 mb-1">已替换内容</p>
                    <p id="infoReplacedCount" class="text-2xl font-bold text-purple-500">0 处</p>
                </div>
            </div>
            
            <div class="mt-6">
                <h3 class="text-lg font-medium mb-2">替换历史</h3>
                <div id="replaceHistory" class="bg-gray-50 rounded-lg p-3 h-32 overflow-y-auto text-sm">
                    <p class="text-gray-500 italic">暂无替换记录</p>
                </div>
            </div>
        </section>

        <!-- 页脚 -->
        <footer class="mt-12 text-center text-gray-500 text-sm">
            <p>批量文字替换工具 &copy; 2023 | 设计与开发</p>
        </footer>
    </div>

    <script>
        // DOM元素引用
        const addRuleBtn = document.getElementById('addRule');
        const replaceBtn = document.getElementById('replaceBtn');
        const clearRulesBtn = document.getElementById('clearRules');
        const clearTextsBtn = document.getElementById('clearTexts');
        const loadExampleBtn = document.getElementById('loadExample');
        const rulesContainer = document.getElementById('rulesContainer');
        const originalText = document.getElementById('originalText');
        const resultText = document.getElementById('resultText');
        const copyResultBtn = document.getElementById('copyResult');
        const copyNotification = document.getElementById('copyNotification');
        const originalWordCount = document.getElementById('originalWordCount');
        const resultWordCount = document.getElementById('resultWordCount');
        const ruleCount = document.getElementById('ruleCount');
        const infoOriginalCount = document.getElementById('infoOriginalCount');
        const infoResultCount = document.getElementById('infoResultCount');
        const infoRuleCount = document.getElementById('infoRuleCount');
        const infoReplacedCount = document.getElementById('infoReplacedCount');
        const replaceHistory = document.getElementById('replaceHistory');
        
        // 预设颜色数量
        const COLOR_COUNT = 8;
        
        // 统计字数
        function updateWordCounts() {
            // 获取纯文本内容计算字数
            const originalCount = originalText.textContent.trim().length;
            const resultCount = resultText.textContent.trim().length;
            
            originalWordCount.textContent = `${originalCount} 个字`;
            resultWordCount.textContent = `${resultCount} 个字`;
            infoOriginalCount.textContent = originalCount;
            infoResultCount.textContent = resultCount;
        }
        
        // 更新规则计数
        function updateRuleCount() {
            const count = rulesContainer.querySelectorAll('.rule-row').length;
            ruleCount.textContent = `${count} 条规则`;
            infoRuleCount.textContent = count;
            
            // 控制删除按钮状态
            const deleteButtons = rulesContainer.querySelectorAll('.delete-rule button');
            deleteButtons.forEach(btn => {
                btn.disabled = count <= 1;
                btn.classList.toggle('disabled:opacity-30', count <= 1);
                btn.classList.toggle('disabled:cursor-not-allowed', count <= 1);
            });
        }
        
        // 初始化颜色选择器事件
        function initColorSelector(row) {
            const colorOptions = row.querySelectorAll('.color-option');
            const colorValue = row.querySelector('.color-value');
            
            colorOptions.forEach(option => {
                option.addEventListener('click', () => {
                    // 移除其他选项的选中状态
                    colorOptions.forEach(opt => opt.classList.remove('selected'));
                    // 设置当前选项为选中
                    option.classList.add('selected');
                    // 更新隐藏字段的值
                    colorValue.value = option.dataset.color;
                });
            });
        }
        
        // 添加新的替换规则行
        function addRuleRow(fromText = '', toText = '', color = null) {
            // 如果没有指定颜色，自动选择下一个可用颜色
            if (color === null) {
                const rowCount = rulesContainer.querySelectorAll('.rule-row').length;
                color = rowCount % COLOR_COUNT;
            }
            
            const newRow = document.createElement('div');
            newRow.className = 'rule-row flex flex-wrap gap-3 items-end animate-fadeIn';
            newRow.innerHTML = `
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-1">要替换的内容</label>
                    <input type="text" class="from-text w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" placeholder="输入要替换的文字" value="${fromText}">
                </div>
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-1">替换后的内容</label>
                    <input type="text" class="to-text w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all" placeholder="输入替换后的文字" value="${toText}">
                </div>
                <div class="color-selector min-w-[180px]">
                    <label class="block text-sm font-medium text-gray-700 mb-1">选择高亮颜色</label>
                    <div class="flex gap-2">
                        <div class="color-option highlight-color-0 ${color == 0 ? 'selected' : ''}" data-color="0"></div>
                        <div class="color-option highlight-color-1 ${color == 1 ? 'selected' : ''}" data-color="1"></div>
                        <div class="color-option highlight-color-2 ${color == 2 ? 'selected' : ''}" data-color="2"></div>
                        <div class="color-option highlight-color-3 ${color == 3 ? 'selected' : ''}" data-color="3"></div>
                        <div class="color-option highlight-color-4 ${color == 4 ? 'selected' : ''}" data-color="4"></div>
                    </div>
                    <input type="hidden" class="color-value" value="${color}">
                </div>
                <div class="delete-rule self-center opacity-50 hover:opacity-100 transition-opacity">
                    <button class="p-2 text-gray-500 hover:text-red-500">
                        <i class="fa fa-times-circle"></i>
                    </button>
                </div>
            `;
            
            // 初始化颜色选择器
            initColorSelector(newRow);
            
            // 添加删除事件
            newRow.querySelector('.delete-rule button').addEventListener('click', () => {
                newRow.classList.add('opacity-0', 'scale-95');
                newRow.style.transition = 'all 0.2s ease-out';
                setTimeout(() => {
                    newRow.remove();
                    updateRuleCount();
                }, 200);
            });
            
            rulesContainer.appendChild(newRow);
            updateRuleCount();
            
            // 自动滚动到底部
            rulesContainer.scrollTop = rulesContainer.scrollHeight;
        }
        
        // 对文本中的特定内容添加高亮
        function highlightText(text, search, colorIndex) {
            if (!search) return text;
            
            // 转义特殊正则字符
            const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(`(${escapedSearch})`, 'g');
            
            // 替换匹配的文本，添加高亮标签
            return text.replace(regex, `<span class="highlight highlight-color-${colorIndex}">$1</span>`);
        }
        
        // 执行替换操作 - 所有规则都基于原始文本进行替换
        function performReplace() {
            // 获取原始文本（纯文本）
            const originalPlainText = originalText.textContent;
            let resultPlainText = originalPlainText;
            let totalReplacements = 0;
            const rules = [];
            
            // 收集所有替换规则
            document.querySelectorAll('.rule-row').forEach(row => {
                const from = row.querySelector('.from-text').value.trim();
                const to = row.querySelector('.to-text').value;
                const color = row.querySelector('.color-value').value;
                
                if (from) { // 只处理非空的替换规则
                    rules.push({ from, to, color });
                }
            });
            
            // 先处理原始文本的高亮显示
            let highlightedOriginal = originalPlainText;
            rules.forEach(({ from, color }) => {
                if (from && highlightedOriginal.includes(from)) {
                    highlightedOriginal = highlightText(highlightedOriginal, from, color);
                }
            });
            
            // 创建位置标记系统，确保所有替换都基于原始文本
            // 记录所有需要替换的位置和内容
            const replacements = [];
            
            rules.forEach(({ from, to }) => {
                if (!from) return;
                
                const escapedFrom = from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                const regex = new RegExp(escapedFrom, 'g');
                let match;
                
                // 记录所有匹配项的位置和替换内容
                while ((match = regex.exec(originalPlainText)) !== null) {
                    // 检查这个位置是否已经被其他规则标记
                    const isOverlapping = replacements.some(r => 
                        !(match.index >= r.end || regex.lastIndex <= r.start)
                    );
                    
                    // 如果不重叠，添加这个替换
                    if (!isOverlapping) {
                        replacements.push({
                            start: match.index,
                            end: regex.lastIndex,
                            original: match[0],
                            replacement: to
                        });
                        totalReplacements++;
                    }
                }
            });
            
            // 按位置排序替换项
            replacements.sort((a, b) => a.start - b.start);
            
            // 应用所有替换
            let result = '';
            let lastIndex = 0;
            
            replacements.forEach(replacement => {
                // 添加上次替换到当前替换之间的文本
                result += originalPlainText.substring(lastIndex, replacement.start);
                // 添加替换后的文本
                result += replacement.replacement;
                // 更新上次替换位置
                lastIndex = replacement.end;
            });
            
            // 添加剩余文本
            result += originalPlainText.substring(lastIndex);
            resultPlainText = result;
            
            // 对替换后的文本进行高亮
            let highlightedResult = resultPlainText;
            rules.forEach(({ to, color, from }) => {
                if (to && highlightedResult.includes(to)) {
                    // 确保我们只高亮实际被替换的内容
                    highlightedResult = highlightText(highlightedResult, to, color);
                }
            });
            
            // 更新显示
            originalText.innerHTML = highlightedOriginal || '<div class="min-h-full text-gray-400">请输入或粘贴需要处理的文本...</div>';
            resultText.innerHTML = highlightedResult || '<div class="min-h-full text-gray-400">替换后的文本将显示在这里...</div>';
            infoReplacedCount.textContent = `${totalReplacements} 处`;
            
            // 更新字数统计
            updateWordCounts();
            
            // 添加到历史记录
            addToHistory(rules.length, totalReplacements);
            
            // 添加替换动画效果
            resultText.classList.add('bg-green-50');
            setTimeout(() => {
                resultText.classList.remove('bg-green-50');
            }, 500);
        }
        
        // 添加到历史记录
        function addToHistory(ruleCount, replacementCount) {
            const now = new Date();
            const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
            
            const historyItem = document.createElement('p');
            historyItem.className = 'mb-1 last:mb-0';
            
            if (replacementCount > 0) {
                historyItem.innerHTML = `<span class="text-gray-600">[${timeString}]</span> 使用 <span class="text-primary font-medium">${ruleCount}</span> 条规则，完成 <span class="text-green-600 font-medium">${replacementCount}</span> 处替换`;
            } else {
                historyItem.innerHTML = `<span class="text-gray-600">[${timeString}]</span> 使用 <span class="text-primary font-medium">${ruleCount}</span> 条规则，未发现可替换内容`;
            }
            
            // 如果是"暂无替换记录"，先清空
            if (replaceHistory.querySelector('p.italic')) {
                replaceHistory.innerHTML = '';
            }
            
            replaceHistory.appendChild(historyItem);
            replaceHistory.scrollTop = replaceHistory.scrollHeight;
        }
        
        // 清空所有规则（保留一行空规则）
        function clearAllRules() {
            // 保留一行并清空内容
            const rows = rulesContainer.querySelectorAll('.rule-row');
            rows.forEach((row, index) => {
                if (index === 0) {
                    row.querySelector('.from-text').value = '';
                    row.querySelector('.to-text').value = '';
                    // 重置颜色选择
                    const colorOptions = row.querySelectorAll('.color-option');
                    colorOptions.forEach(opt => opt.classList.remove('selected'));
                    colorOptions[0].classList.add('selected');
                    row.querySelector('.color-value').value = '0';
                } else {
                    row.remove();
                }
            });
            
            updateRuleCount();
            
            // 添加动画效果
            rulesContainer.classList.add('bg-amber-50');
            setTimeout(() => {
                rulesContainer.classList.remove('bg-amber-50');
            }, 500);
        }
        
        // 清空所有文本
        function clearAllTexts() {
            originalText.innerHTML = '<div class="min-h-full text-gray-400">请输入或粘贴需要处理的文本...</div>';
            resultText.innerHTML = '<div class="min-h-full text-gray-400">替换后的文本将显示在这里...</div>';
            infoReplacedCount.textContent = '0 处';
            updateWordCounts();
            
            // 添加动画效果
            originalText.classList.add('bg-red-50');
            resultText.classList.add('bg-red-50');
            setTimeout(() => {
                originalText.classList.remove('bg-red-50');
                resultText.classList.remove('bg-red-50');
            }, 500);
        }
        
        // 加载示例文本和规则 - 包含您提到的测试案例
        function loadExample() {
            // 示例文本 - 使用您提到的测试案例
            originalText.textContent = `昨天的你是今天的你，也是前天的你。`;
            
            // 清空现有规则
            const rows = rulesContainer.querySelectorAll('.rule-row');
            rows.forEach((row, index) => {
                if (index > 0) row.remove();
            });
            
            // 设置示例规则
            const firstRow = rulesContainer.querySelector('.rule-row');
            firstRow.querySelector('.from-text').value = '昨天';
            firstRow.querySelector('.to-text').value = '今天';
            // 设置颜色
            setColorForRow(firstRow, 0);
            
            // 添加第二条规则
            addRuleRow('今天', '昨天', 1);
            
            // 执行一次替换
            performReplace();
            
            // 更新计数
            updateWordCounts();
            
            // 添加动画效果
            originalText.classList.add('bg-blue-50');
            rulesContainer.classList.add('bg-blue-50');
            setTimeout(() => {
                originalText.classList.remove('bg-blue-50');
                rulesContainer.classList.remove('bg-blue-50');
            }, 500);
        }
        
        // 为规则行设置颜色
        function setColorForRow(row, colorIndex) {
            const colorOptions = row.querySelectorAll('.color-option');
            colorOptions.forEach(opt => opt.classList.remove('selected'));
            colorOptions[colorIndex].classList.add('selected');
            row.querySelector('.color-value').value = colorIndex;
        }
        
        // 复制结果到剪贴板（只复制纯文本）
        function copyResultToClipboard() {
            // 获取纯文本内容
            const text = resultText.textContent;
            
            // 创建临时元素用于复制
            const tempElement = document.createElement('textarea');
            tempElement.value = text;
            document.body.appendChild(tempElement);
            
            // 复制并清理
            tempElement.select();
            document.execCommand('copy');
            document.body.removeChild(tempElement);
            
            // 显示复制成功提示
            copyNotification.classList.remove('hidden');
            setTimeout(() => {
                copyNotification.classList.add('hidden');
            }, 2000);
        }
        
        // 事件监听
        addRuleBtn.addEventListener('click', () => addRuleRow());
        replaceBtn.addEventListener('click', performReplace);
        clearRulesBtn.addEventListener('click', clearAllRules);
        clearTextsBtn.addEventListener('click', clearAllTexts);
        loadExampleBtn.addEventListener('click', loadExample);
        copyResultBtn.addEventListener('click', copyResultToClipboard);
        
        // 实时更新字数统计
        originalText.addEventListener('input', updateWordCounts);
        resultText.addEventListener('input', updateWordCounts);
        
        // 初始化第一条规则的颜色选择器
        initColorSelector(rulesContainer.querySelector('.rule-row'));
        
        // 初始化
        updateWordCounts();
        updateRuleCount();
        
        // 添加键盘快捷键
        document.addEventListener('keydown', (e) => {
            // Ctrl+Enter 执行替换
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                performReplace();
            }
            
            // Ctrl+Shift+C 复制结果
            if (e.ctrlKey && e.shiftKey && e.key === 'C') {
                e.preventDefault();
                copyResultToClipboard();
            }
        });
    </script>
</body>
</html>
